package cn.hg.solon.youcan.framework.config;

import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.auth.AuthAdapter;
import org.noear.solon.auth.AuthProcessor;
import org.noear.solon.auth.annotation.Logical;

import cn.dev33.satoken.stp.StpUtil;

/**
 * SA-Token到solon.auth注解与模板标签能力的桥接配置
 *
 * @author 胡高
 */
@Configuration
public class AuthBridgingConfig {
    public static class AuthProcessorImpl implements AuthProcessor {
        @Override
        public boolean verifyIp(String ip) {
            return false;
        }

        @Override
        public boolean verifyLogined() {
            return StpUtil.isLogin();
        }

        @Override
        public boolean verifyPath(String path, String method) {
            return false;
        }

        @Override
        public boolean verifyPermissions(String[] permissions, Logical logical) {
            if (Logical.AND == logical) {
                return StpUtil.hasPermissionAnd(permissions);
            } else {
                return StpUtil.hasPermissionOr(permissions);
            }
        }

        @Override
        public boolean verifyRoles(String[] roles, Logical logical) {
            if (Logical.AND == logical) {
                return StpUtil.hasRoleAnd(roles);
            } else {
                return StpUtil.hasRoleOr(roles);
            }
        }
    }

    @Bean
    public AuthAdapter initAuth() {
        return new AuthAdapter().processor(new AuthProcessorImpl()) // 设定认证处理器
            .failure((ctx, rst) -> {
                // 设定默认的验证失败处理
                ctx.render(rst);
            });
    }
}
